/*
 * hackds/course_design/voldemort_language/src/rule_mean.c
 *
 * (C) 2011 Harry Wei
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <stdint.h>

#include "../include/vl.h"

int 
rd_file(char *r_file, char *i_file, struct rule **regu, 
	struct mean **implication, int *r_counter, int *i_counter)
{
	int i = 0;
	int r_fd;
	int i_fd;
	int check;
	int reg_counter = 0;
	int counter = 0;
	char ch;
	char r_buf[BUF];
	char i_buf[BUF];

	if (0 > (r_fd = open(r_file, O_RDONLY))) {
		fprintf(stderr, "Open File Error!\n");
		return 1;
	}
	if (0 > (i_fd = open(i_file, O_RDONLY))) {
		fprintf(stderr, "Open File Error!\n");
		return 1;
	}
	while (check = read(r_fd, &ch, sizeof(char))) {
		if (check != sizeof(char)) {
			fprintf(stderr, "Read Error!\n");
			return 1;
		}
		if (('A' <= ch && ch <= 'Z') ||
			('a' <= ch && ch <= 'z') || ':' == ch) {
			r_buf[counter] = ch;
			counter += 1;
		} else {
			continue;
		}
	}
	r_buf[counter] = '\0';
	counter = (int)0;
	while (check = read(i_fd, &ch, sizeof(char))) {
		if (check != sizeof(char)) {
			fprintf(stderr, "Read Error!\n");
			return 1;
		}
		if (('a' <= ch && ch <= 'z') || ':' == ch) {
			i_buf[counter] = ch;
			counter += 1;
		} else {
			continue;
		}
	}
	i_buf[counter] = '\0';
	counter = (int)0;
	while (r_buf[i]) {
		if (':' == r_buf[i]) {
			counter += 1;
			i += 1;
		} else {
			i += 1;
			continue;
		}
	} 
	*r_counter = counter;
	(*regu) = (struct rule *)malloc(sizeof(struct rule) * counter);
	if (!(*regu)) {
		fprintf(stderr, "Allocate Error!\n");
		return 1;
	}
	i = (int)0;
	counter = -1;
	while (r_buf[i]) {
		if (':' == r_buf[i]) {
			counter += 1;
			(*regu)[counter].upper_ch = r_buf[i - 1];
			i += 1;
			reg_counter = 0;
			continue;
		} else {
			if (':' != r_buf[i + 1]) {
				(*regu)[counter].reg[reg_counter] = r_buf[i];
				reg_counter += 1;
				i += 1;
				continue;
			} else {
				i += 1;
				continue;
			}
		}
	}
	i = (int)0;
	counter = (int)0;
	while (i_buf[i]) {
		if (':' == i_buf[i]) {
			counter += 1;
			i += 1;
		} else {
			i += 1;
			continue;
		}
	} 
	*i_counter = counter;
	(*implication) = (struct mean *)malloc(sizeof(struct mean) * counter);
	if (!(*implication)) {
		fprintf(stderr, "Allocate Error!\n");
		return 1;
	}
	i = (int)0;
	counter = -1;
	while (i_buf[i]) {
		if (':' == i_buf[i]) {
			counter += 1;
			(*implication)[counter].lower_ch = i_buf[i - 1];
			i += 1;
			reg_counter = 0;
			continue;
		} else {
			if (':' != i_buf[i + 1]) {
				(*implication)[counter].meaning[reg_counter] = i_buf[i];
				reg_counter += 1;
				i += 1;
				continue;
			} else {
				i += 1;
				continue;
			}
		}
	}
	if (close(r_fd)) {
		fprintf(stderr, "Close Error!\n");
		return 1;
	}
	if (close(i_fd)) {
		fprintf(stderr, "Close Error!\n");
		return 1;
	}
	return 0;
}
